/**
 * Validates image dimensions
 * @param width Image width
 * @param height Image height
 * @param maxWidth Maximum allowed width
 * @param maxHeight Maximum allowed height
 * @returns Object with validation result and error message
 */
export function validateImageDimensions(
  width: number, 
  height: number, 
  maxWidth = 12000, 
  maxHeight = 12000
): { valid: boolean; message?: string } {
  // Check if dimensions are valid
  if (width <= 0 || height <= 0) {
    return { valid: false, message: '图片尺寸无效' };
  }
  
  // Check if dimensions are within limits
  if (width > maxWidth) {
    return { valid: false, message: `图片宽度超过最大限制 (${maxWidth}px)` };
  }
  
  if (height > maxHeight) {
    return { valid: false, message: `图片高度超过最大限制 (${maxHeight}px)` };
  }
  
  return { valid: true };
}

/**
 * Validates total number of images
 * @param count Current number of images
 * @param adding Number of images being added
 * @param maxCount Maximum allowed number of images
 * @returns Object with validation result and error message
 */
export function validateImageCount(
  count: number, 
  adding: number, 
  maxCount = 100
): { valid: boolean; message?: string } {
  const totalCount = count + adding;
  
  if (totalCount > maxCount) {
    return { valid: false, message: `最多只能上传 ${maxCount} 张图片` };
  }
  
  return { valid: true };
}

/**
 * Validates total stitched image size
 * @param images Array of image dimensions {width, height}
 * @param spacing Spacing between images
 * @param arrangement Arrangement type
 * @param maxWidth Maximum allowed width
 * @param maxHeight Maximum allowed height
 * @returns Object with validation result and error message
 */
export function validateStitchedImageSize(
  images: Array<{width: number; height: number}>,
  spacing: number,
  arrangement: 'grid' | 'horizontal' | 'vertical' | 'dynamic',
  maxWidth = 12000,
  maxHeight = 12000
): { valid: boolean; message?: string; estimatedSize?: {width: number; height: number} } {
  if (images.length === 0) {
    return { valid: true, estimatedSize: {width: 0, height: 0} };
  }
  
  let totalWidth = 0;
  let totalHeight = 0;
  
  if (arrangement === 'horizontal') {
    // All images in a row
    totalWidth = images.reduce((sum, img) => sum + img.width, 0) + (spacing * (images.length - 1));
    totalHeight = Math.max(...images.map(img => img.height));
  } else if (arrangement === 'vertical') {
    // All images in a column
    totalWidth = Math.max(...images.map(img => img.width));
    totalHeight = images.reduce((sum, img) => sum + img.height, 0) + (spacing * (images.length - 1));
  } else if (arrangement === 'dynamic') {
    // 动态布局 - 尝试创建接近正方形的布局
    // 将图片分为横向和纵向两组
    const landscapeImages = images.filter(img => img.width > img.height);
    const portraitImages = images.filter(img => img.height > img.width);
    
    // 检查是否所有图片尺寸相似
    const isLandscapeSimilar = areSimilarSizes(landscapeImages);
    const isPortraitSimilar = areSimilarSizes(portraitImages);
    
    // 如果横向和纵向图片都有，并且尺寸相似，尝试创建接近正方形的布局
    if (landscapeImages.length > 0 && portraitImages.length > 0 && 
        isLandscapeSimilar && isPortraitSimilar) {
      
      // 获取典型图片尺寸
      const typicalLandscape = landscapeImages[0];
      const typicalPortrait = portraitImages[0];
      
      // 检查横向图片的宽是否约等于纵向图片的高，横向图片的高是否约等于纵向图片的宽
      const isComplementary = Math.abs(typicalLandscape.width - typicalPortrait.height) < 100 &&
                             Math.abs(typicalLandscape.height - typicalPortrait.width) < 100;
      
      if (isComplementary) {
        // 创建接近正方形的布局
        // 计算每行可以放置的图片数量
        const landscapeWidth = typicalLandscape.width;
        const imagesPerRow = Math.floor(12000 / landscapeWidth);
        
        // 计算总行数
        const totalImages = landscapeImages.length + portraitImages.length;
        const totalRows = Math.ceil(totalImages / imagesPerRow);
        
        // 估算宽度和高度（不限制为12000）
        const rawWidth = imagesPerRow * landscapeWidth + (imagesPerRow - 1) * spacing;
        const rawHeight = totalRows * typicalLandscape.height + (totalRows - 1) * spacing;
        
        // 如果宽高比接近1:1，则认为是接近正方形的布局
        const aspectRatio = rawWidth / rawHeight;
        if (aspectRatio >= 0.9 && aspectRatio <= 1.1) {
          // 检查是否超出限制
          if (rawWidth > maxWidth || rawHeight > maxHeight) {
            return { 
              valid: false, 
              message: `拼接后的图片尺寸 (${Math.ceil(rawWidth)}x${Math.ceil(rawHeight)}px) 超过最大限制 (${maxWidth}x${maxHeight}px)`,
              estimatedSize: {width: Math.ceil(rawWidth), height: Math.ceil(rawHeight)}
            };
          }
          
          totalWidth = rawWidth;
          totalHeight = rawHeight;
          return { valid: true, estimatedSize: {width: totalWidth, height: totalHeight} };
        }
      }
    }
    
    // 如果不是特殊情况，使用默认的网格布局
    const count = images.length;
    const sqrt = Math.sqrt(count);
    const cols = Math.ceil(sqrt);
    
    let currentX = 0;
    let currentY = 0;
    let maxRowHeight = 0;
    let calculatedMaxWidth = 0;
    
    for (let i = 0; i < images.length; i++) {
      const image = images[i];
      
      // If we've reached the end of a row, move to the next row
      if (i > 0 && i % cols === 0) {
        currentX = 0;
        currentY += maxRowHeight + spacing;
        maxRowHeight = 0;
      }
      
      currentX += image.width + spacing;
      maxRowHeight = Math.max(maxRowHeight, image.height);
      calculatedMaxWidth = Math.max(calculatedMaxWidth, currentX - spacing);
    }
    
    totalWidth = calculatedMaxWidth;
    totalHeight = currentY + maxRowHeight;
  } else {
    // Grid arrangement
    const count = images.length;
    const sqrt = Math.sqrt(count);
    const cols = Math.ceil(sqrt);
    // We calculate rows but don't use it directly in the algorithm below
    // as we're tracking row heights dynamically
    
    // Use the same algorithm as the worker for more accurate size estimation
    let currentX = 0;
    let currentY = 0;
    let maxRowHeight = 0;
    let calculatedMaxWidth = 0;
    
    for (let i = 0; i < images.length; i++) {
      const image = images[i];
      
      // If we've reached the end of a row, move to the next row
      if (i > 0 && i % cols === 0) {
        currentX = 0;
        currentY += maxRowHeight + spacing;
        maxRowHeight = 0;
      }
      
      currentX += image.width + spacing;
      maxRowHeight = Math.max(maxRowHeight, image.height);
      calculatedMaxWidth = Math.max(calculatedMaxWidth, currentX - spacing);
    }
    
    totalWidth = calculatedMaxWidth;
    totalHeight = currentY + maxRowHeight;
  }
  
  const estimatedSize = {width: Math.ceil(totalWidth), height: Math.ceil(totalHeight)};
  
  if (totalWidth > maxWidth) {
    return { 
      valid: false, 
      message: `拼接后的图片宽度 (${Math.ceil(totalWidth)}px) 超过最大限制 (${maxWidth}px)`,
      estimatedSize
    };
  }
  
  if (totalHeight > maxHeight) {
    return { 
      valid: false, 
      message: `拼接后的图片高度 (${Math.ceil(totalHeight)}px) 超过最大限制 (${maxHeight}px)`,
      estimatedSize
    };
  }
  
  return { valid: true, estimatedSize };
}
/**
 
* 检查一组图片的尺寸是否相似
 * @param images 图片数组
 * @returns 是否相似
 */
function areSimilarSizes(images: Array<{ width: number; height: number }>): boolean {
  if (images.length <= 1) return true;

  const firstWidth = images[0].width;
  const firstHeight = images[0].height;

  // 允许10%的误差
  const tolerance = 0.1;

  return images.every(img =>
    Math.abs(img.width - firstWidth) / firstWidth < tolerance &&
    Math.abs(img.height - firstHeight) / firstHeight < tolerance
  );
}